import tkinter as tk
from tkinter import ttk, scrolledtext
from datetime import datetime

class TempIconWindow(tk.Toplevel):
    """独立窗口：用图标化方式展示温度数据"""
    def __init__(self, parent, city, data):
        super().__init__(parent)
        self.title(f"{city} 温度图标")
        self.geometry("400x600")
        self.resizable(True, True)
        self.data = data or []

        self.create_widgets()
        self.populate_icons()

    def create_widgets(self):
        # 顶部标题
        ttk.Label(self, text="📅 每日温度速览", font=("微软雅黑", 14)).pack(pady=5)

        # 滚动文本框，只读
        self.txt = scrolledtext.ScrolledText(
            self,
            wrap=tk.WORD,
            font=("微软雅黑", 12),
            bg="#f0f0f0",
            relief=tk.FLAT,
            state=tk.DISABLED
        )
        self.txt.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 底部关闭按钮
        ttk.Button(self, text="关闭", command=self.destroy).pack(pady=5)

    def populate_icons(self):
        """把温度数据变成图标化文本写入"""
        if not self.data:
            self.write_line("暂无温度数据")
            return

        for rec in self.data:
            date = rec["date"].strftime("%m月%d日")
            high = rec["high"]
            low = rec["low"]
            weather = rec["weather"]

            # 温度计 emoji + 温度条
            temp_bar = self.temp_bar(high, low)
            line = f"{date}  {temp_bar}  {high}°/{low}°  {weather}\n"
            self.write_line(line)

    def temp_bar(self, high, low):
        """生成彩色温度条 emoji"""
        # 用颜色深浅表示高低温
        if high >= 35:
            color = "🔴"
        elif high >= 25:
            color = "🟠"
        elif high >= 15:
            color = "??"
        elif high >= 5:
            color = "🟢"
        else:
            color = "🔵"

        # 用温度计个数表示温差大小
        diff = max(high - low, 1)
        count = min(int(diff // 3 + 1), 5)
        return color + "🌡️" * count

    def write_line(self, text):
        """往只读 ScrolledText 插入一行"""
        self.txt.config(state=tk.NORMAL)
        self.txt.insert(tk.END, text)
        self.txt.config(state=tk.DISABLED)
        self.txt.see(tk.END)